<template>
    <div class="register-container">
        <el-card class="register-card">
            <h3 class="register-title">用户注册</h3>
            <el-form ref="ruleFormRef" :model="registerForm" :rules="rules" label-width="75px" class="demo-ruleForm"
                :size="formSize" status-icon>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="registerForm.username" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="registerForm.password" show-password />
                </el-form-item>
                <el-form-item label="手机" prop="telephone">
                    <el-input v-model="registerForm.phoneNumber" style="width:140px" />
                    <el-button :disabled="countdown > 0" @click="openSlider">{{ countdownText }}</el-button>
                    <el-dialog v-model="showSlider" width="25%" center>
                        <SliedComponent @successEvent="getSmsVerifyCode" @startCountdown="startCountdown"></SliedComponent>
                    </el-dialog>
                </el-form-item>
                <el-form-item label="验证码" prop="verifyCode">
                    <el-input v-model="registerForm.verifyCode" style="width:183px" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        注册
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>
    
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage, ElNotification, type FormInstance, type FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import api from '@/api'
import SliedComponent from '@/components/layout/SliedComponent.vue'

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const registerForm = ref({
    username: '',
    password: '',
    verifyCode: '',
    phoneNumber: ''
})

const rules = reactive<FormRules>({
    username: [
        {
            required: true,
            message: '用户名不能为空',
            trigger: 'change',
        },
    ],
    password: [
        {
            required: true,
            message: '密码不能为空',
            trigger: 'change',
        },
    ],
    phoneNumber: [
        { required: true, message: '手机号必填', trigger: 'blur' },
        { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
    ],
    verifyCode: [
        {
            required: true,
            message: '验证码不能为空',
            trigger: 'change',
        },
    ]
})

const router = useRouter();

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            api.login.register(registerForm.value)
                .then(response => {
                    // 在这里可以处理提交成功后的逻辑
                    ElNotification({
                        title: 'Success',
                        message: response.data.msg,
                        type: 'success',
                        duration: 1500
                    })
                    router.push('/login')

                })
                .catch(error => {
                    ElNotification({
                        title: 'Error',
                        message: error.data.msg,
                        type: 'error',
                        duration: 1500
                    })
                    // 在这里可以处理提交失败后的逻辑
                });
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const showSlider = ref(false)
const countdown = ref(0);
const countdownText = ref("获取验证码");

const openSlider = () => {
    if(registerForm.value.phoneNumber === ''){
        ElMessage.error('手机号不可为空')
        return;
    }
    showSlider.value = true
}

const startCountdown = () => {
    if (countdown.value > 0) {
        return;
      }
      countdown.value = 60;
      countdownText.value = `${countdown.value}秒`;
      const timer = setInterval(() => {
        countdown.value--;
        countdownText.value = `${countdown.value}秒`;
        if (countdown.value === 0) {
          clearInterval(timer);
          countdownText.value = '获取验证码';
        }
      }, 1000);
}

const getSmsVerifyCode = async () => {
    showSlider.value = false
    api.login.getSmsVerifyCode({ "phoneNumber": registerForm.value.phoneNumber,type:'register' })
        .then(response => {
            // 在这里可以处理提交成功后的逻辑
            ElNotification({
                title: 'Success',
                message: response.data.msg,
                type: 'success',
                duration: 1500
            })
        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            })
            // 在这里可以处理提交失败后的逻辑
        });
}

</script>

<style scoped>
.register-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.register-card {
    width: 400px;
    padding: 20px;
}

.register-title {
    text-align: center;
    margin-bottom: 20px;
}
</style>